﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Runtime.InteropServices.Automation;
using bdnt_pets_system.Tools;
using bdnt_pets_system.UploadFileServiceReference;
using System.Windows.Media.Imaging;
using bdnt_pets_system.Resources;

namespace bdnt_pets_system.PageViews.FailuresTraking
{
    public partial class TrakingAttachmentControl : BaseUserControl
    {
        UploadFileServiceReference.UploadFileServiceClient uClient;
        public Tbl_TrakingAttachment CuAttachment;
        FailureServiceReference.FailureServiceClient fClient;
        public TrakingAttachmentControl()
        {
            InitializeComponent();
            fClient = new FailureServiceReference.FailureServiceClient();
            uClient = new UploadFileServiceReference.UploadFileServiceClient();
            CuAttachment = new Tbl_TrakingAttachment();
            InitEvent();
        }

        void InitEvent()
        {
            btnLl.Click += new RoutedEventHandler(btnLl_Click);
            btnUp.Click += new RoutedEventHandler(btnUp_Click);
            uClient.GetTrakingAttachmentByConditionCompleted += new EventHandler<GetTrakingAttachmentByConditionCompletedEventArgs>(uClient_GetTrakingAttachmentByConditionCompleted);
            uClient.UploadFileCompleted += new EventHandler<UploadFileCompletedEventArgs>(us_UploadFileCompleted);
            uClient.DeleteTrakingAttachmentCompleted += new EventHandler<DeleteTrakingAttachmentCompletedEventArgs>(uClient_DeleteTrakingAttachmentCompleted);
            uClient.SetDefaultImgCompleted += new EventHandler<SetDefaultImgCompletedEventArgs>(uClient_SetDefaultImgCompleted);
            uClient.GetDefaultImgCompleted += new EventHandler<GetDefaultImgCompletedEventArgs>(uClient_GetDefaultImgCompleted);
        }

        void uClient_GetDefaultImgCompleted(object sender, GetDefaultImgCompletedEventArgs e)
        {
            var item = e.Result;
            if (e.UserState != null && e.UserState.ToString() == "1")
            {
                var cuo = this.Tag as TrakingDescrWindow;
                if (item != null && item.Length > 0)
                {
                    BitmapImage b = new BitmapImage();
                    Stream mm = new MemoryStream();
                    mm.Write(item, 0, item.Length);
                    b.SetSource(mm);
                    cuo.imgDefault.Source = b;
                    mm.Close();
                    mm.Dispose();
                    cuo.imgDefault.Visibility = System.Windows.Visibility.Visible;
                    cuo.txtDefaultImgShow.Visibility = System.Windows.Visibility.Collapsed;
                    cuo.txtDefaultImgShow.Text = "";
                }
                else cuo.txtDefaultImgShow.Text = MyStrings.wmrtp;//"无默认图片"
            }
            else
            {
                if (item != null && item.Length > 0)
                {

                    BitmapImage b = new BitmapImage();
                    Stream mm = new MemoryStream();
                    mm.Write(item, 0, item.Length);
                    b.SetSource(mm);
                    imgDefault.Source = b;
                    mm.Close();
                    mm.Dispose();

                    imgDefault.Visibility = System.Windows.Visibility.Visible;
                    txtImgShow.Visibility = System.Windows.Visibility.Collapsed;
                    txtImgShow.Text = "";

                    (e.UserState as Tbl_TrakingAttachment).FileData = item;
                }
                else txtImgShow.Text = MyStrings.wtp;// "无图片";
            }
        }

        void uClient_SetDefaultImgCompleted(object sender, SetDefaultImgCompletedEventArgs e)
        {
            if (e.Result)
                QueryData();
        }

        void uClient_GetTrakingAttachmentByConditionCompleted(object sender, GetTrakingAttachmentByConditionCompletedEventArgs e)
        {
            var res = e.Result;
            gdList.ItemsSource = res;

            if (e.UserState != null && bool.Parse(e.UserState.ToString()))
                return;

            var item = res.FirstOrDefault(p => p.IsDefault);
            if (item != null)
            {
                var cuo = this.Tag as TrakingDescrWindow;
                cuo.imgDefault.Visibility = System.Windows.Visibility.Collapsed;
                cuo.txtDefaultImgShow.Visibility = System.Windows.Visibility.Visible;
                cuo.txtDefaultImgShow.Text = MyStrings.tpjzz;// "图片加载中...";

                uClient.GetDefaultImgAsync(item, 1);
                //var cuo = this.Tag as TrakingDescrWindow;
                //BitmapImage b = new BitmapImage();
                //Stream mm = new MemoryStream();
                //mm.Write(item.FileData, 0, item.FileData.Length);
                //b.SetSource(mm);
                //cuo.imgDefault.Source = b;
                //mm.Close();
                //mm.Dispose();
            }

        }

        void uClient_DeleteTrakingAttachmentCompleted(object sender, DeleteTrakingAttachmentCompletedEventArgs e)
        {
            if (e.Result)
                QueryData();
        }

        public void QueryData(bool isUpdate = false)
        {
            uClient.GetTrakingAttachmentByConditionAsync(CuAttachment.TrakingId, SessionManager.PageSize, 1, isUpdate);

        }
        void btnUp_Click(object sender, RoutedEventArgs e)
        {
            if (cuFil == null)
                return;

            if (string.IsNullOrEmpty(tbWjm.Text))
            {
                tbMsg.Text = MyStrings.wjmbnwk;// "文件名不能为空";
                return;
            }


            lock (this)
            {

                if (!string.IsNullOrEmpty(tbWjdz.Text) && cuFil != null)
                {
                    if (string.IsNullOrEmpty(tbWjm.Text))
                    {
                        tbMsg.Text = MyStrings.wjmbnwk;// "文件名不能为空";
                        return;
                    }

                    btnUp.IsEnabled = false;
                    tbMsg.Text = MyStrings.tqscz;// "图片上传中...";

                    CuAttachment.ExtName = cuFil.Extension;
                    CuAttachment.FileName = tbWjm.Text;
                    CuAttachment.IsDefault = false;
                    CuAttachment.UpDateTime = DateTime.Now;
                    CuAttachment.UpUserId = SessionManager.CurrentUser.Id;
                    CuAttachment.FileSize = tbFileSize.Text;

                    Stream stream = cuFil.OpenRead();
                    byte[] buffer = new byte[stream.Length + 1];

                    //将文件读入字节数组
                    stream.Read(buffer, 0, buffer.Length);
                    stream.Close();
                    string fileName = tbWjdz.Text;
                    CuAttachment.FileData = buffer;
                    CuAttachment.FilePath = CuAttachment.TrakingId.ToString();
                    uClient.UploadFileAsync(CuAttachment);
                }
                else
                {
                    tbMsg.Text = MyStrings.qxzwj;// "请先选择文件";
                }
            }
        }

        void us_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
        {
            if (e.Result)
            {
                QueryData(true);
                CuAttachment = new Tbl_TrakingAttachment() { TrakingId = CuAttachment.TrakingId };
                tbWjm.Text = tbWjdz.Text = tbFileSize.Text = "";
                tbMsg.Text = MyStrings.sccg;// "上传成功";
            }
            else
            {
                btnUp.IsEnabled = true;
                tbMsg.Text = MyStrings.scsb;// "上传失败";
            }
        }

        FileInfo cuFil;
        void btnLl_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            if (dialog.ShowDialog() == true)
            {
                Stream stream = dialog.File.OpenRead();
                try
                {
                    if (stream.Length > 4194304)
                    {
                        tbMsg.Text = MyStrings.wj + stream.Length.ToString() + MyStrings.cgzdz4m;// "超过最大值4M";
                        stream.Close();
                        return;
                    }

                    btnUp.IsEnabled = true;
                    tbMsg.Text = "";

                    // 选择上传的文件
                    cuFil = dialog.File;
                    tbWjdz.Text = cuFil.Name;
                    tbWjm.Text = cuFil.Name.Replace(cuFil.Extension, "");
                    tbFileSize.Text = HelpTools.GetFileSize(stream.Length);

                }
                catch (Exception)
                {
                    stream.Close();
                    tbMsg.Text = MyStrings.wjxzyyc;// "文件选择有异常";
                }
                finally
                {
                    stream.Close();
                }
            }
        }

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show(MyStrings.qdyscm,MyStrings.ts, MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                return;
            var cuo = (sender as HyperlinkButton).Tag as Tbl_TrakingAttachment;
            uClient.DeleteTrakingAttachmentAsync(cuo);
        }

        private void HyperlinkButton_Click_1(object sender, RoutedEventArgs e)
        {
            var cuo = (sender as HyperlinkButton).Tag as Tbl_TrakingAttachment;
            uClient.SetDefaultImgAsync(cuo);
        }

        private void gdList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (gdList.SelectedItems.Count < 1)
                return;
            imgDefault.Visibility = System.Windows.Visibility.Collapsed;
            txtImgShow.Visibility = System.Windows.Visibility.Visible;
            txtImgShow.Text = MyStrings.tpjzz;// "图片加载中...";
            var cuo = gdList.SelectedItem as Tbl_TrakingAttachment;
            
            if (cuo.FileData != null && cuo.FileData.Length > 0)
            {
                BitmapImage b = new BitmapImage();
                Stream mm = new MemoryStream();
                mm.Write(cuo.FileData, 0, cuo.FileData.Length);
                b.SetSource(mm);
                imgDefault.Source = b;
                mm.Close();
                mm.Dispose();

                imgDefault.Visibility = System.Windows.Visibility.Visible;
                txtImgShow.Visibility = System.Windows.Visibility.Collapsed;
                txtImgShow.Text = "";
                return;
            }
            if (cuo.FileType == "1")
            {
                uClient.GetDefaultImgAsync(cuo, cuo);
            }
            else
            {
                imgDefault.Visibility = System.Windows.Visibility.Visible;
                txtImgShow.Visibility = System.Windows.Visibility.Collapsed;
                txtImgShow.Text = "";
                return;
            }


        }
    }
}
